//
//  ZCLoadViewController.m
//  VoiceMusic
//
//  Created by dllo on 15/10/24.
//  Copyright © 2015年 zhangdeyu. All rights reserved.
//

#import "ZCLoadViewController.h"
#import <Masonry.h>
#import "ZCLoadCell.h"
#import "ZCDetailListModel.h"


#import "ZCDownLoadTool.h"
#import "FileModel.h"
#import "ZCPlayMusicTool.h"
#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>

#define SAVEDocument [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"video"]
#define LOCALDocument [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"local.plist"]

@interface ZCLoadViewController ()<UITableViewDelegate,UITableViewDataSource,downDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *nowArr;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) NSMutableArray *finshArr;

@property (nonatomic, strong) NSMutableArray *listArr;
@end

@implementation ZCLoadViewController

-(void)viewWillAppear:(BOOL)animated{
    
    [self createDate];
    
    
}
-(void)createDate{
 
    if(self.nowArr != nil) self.nowArr = nil;
    self.nowArr = [NSMutableArray arrayWithArray:[ZCDownLoadTool shareDownLoad].downloadArr];
    if(self.finshArr != nil)self.finshArr = nil;
    self.finshArr = [NSMutableArray array];
   self.finshArr = [NSKeyedUnarchiver unarchiveObjectWithFile:LOCALDocument];
    //防止第一次反归档把数组制空了
    if(self.finshArr == nil){
        self.finshArr = [NSMutableArray array];
    }
    
    NSLog(@"2222%@",self.finshArr);
    
    //检查每次下载的歌曲跟本地歌曲是否有重复的
    if([ZCDownLoadTool shareDownLoad].finishArr.count != 0){
        for (NSInteger i = 0; i < [ZCDownLoadTool shareDownLoad].finishArr.count; i++) {
            ZCDetailListModel * model = [[ZCDetailListModel alloc] init];
             model.name = [(FileModel *)[((ASIHTTPRequest *)[ZCDownLoadTool shareDownLoad].finishArr[i]).userInfo objectForKey:@"File" ] fileName];
            model.singerName = [(FileModel *)[((ASIHTTPRequest *)[ZCDownLoadTool shareDownLoad].finishArr[i]).userInfo objectForKey:@"File" ] sing];
            
            model.auditionList[0][@"url"] = [(FileModel *)[((ASIHTTPRequest *)[ZCDownLoadTool shareDownLoad].finishArr[i]).userInfo objectForKey:@"File" ] fileURL];
            
            BOOL last = YES;
            for (NSInteger j=0; j < self.finshArr.count; j++) {
                ZCDetailListModel *mo = self.finshArr[j];
                if([mo.name isEqualToString:model.name]){
                    last = NO;
                    break;
                }
            }
            if(last){
                [self.finshArr addObject:model];
            }
        }
    }
    
    //将播放列表的数据归档
    NSString *path = LOCALDocument;
    NSLog(@"%@",path);

    [NSKeyedArchiver archiveRootObject:self.finshArr toFile:path];
    NSLog(@"1111%@",self.finshArr);
    
    [ZCDownLoadTool shareDownLoad].delegate = self;
    [self.tableView reloadData];
}

-(void)updateFinishList{
    
    [self createDate];
    [self.tableView reloadData];
    
//    [self getFileSize];
}
-(void)updateFileSize{
//    [self getFileSize];
}
-(void)updateTaskProgress:(ASIHTTPRequest *)request{

}

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
       
        self.listArr = [NSMutableArray array];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //返回键
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [leftButton addTarget:self action:@selector(returnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"3187"]];
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self.editButtonItem setImage:[UIImage imageNamed:@"iconfont-shanchu"]];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 40;
    [self.view addSubview:self.tableView];
    
   
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-49);
    }];
}
#pragma mark 返回
- (void)returnClick:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return self.nowArr.count;
    }else{
        return self.finshArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *re = @"re";
    ZCLoadCell *cell = [tableView dequeueReusableCellWithIdentifier:re];
    if(!cell){
        cell = [[ZCLoadCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:re];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    if(indexPath.section == 0){
        if([ZCDownLoadTool shareDownLoad].downloadArr.count == 0)return cell;
        
        ZCDetailListModel *model = [[ZCDetailListModel alloc] init];
        model.name = [(FileModel *)[((ASIHTTPRequest *)[ZCDownLoadTool shareDownLoad].downloadArr[indexPath.row]).userInfo objectForKey:@"File" ] fileName];
        
        model.singerName = [(FileModel *)[((ASIHTTPRequest *)[ZCDownLoadTool shareDownLoad].downloadArr[indexPath.row]).userInfo objectForKey:@"File" ] sing];
        
        cell.textLabel.text = model.name;
        cell.detailTextLabel.text = model.singerName;
        
    }else{
        if(self.finshArr.count == 0)return cell;
        
        ZCDetailListModel *model = [[ZCDetailListModel alloc] init];
//        model.name = [(FileModel *)[((ASIHTTPRequest *)[ZCDownLoadTool shareDownLoad].finishArr[indexPath.row]).userInfo objectForKey:@"File" ] fileName];
//        
//        model.singerName = [(FileModel *)[((ASIHTTPRequest *)[ZCDownLoadTool shareDownLoad].finishArr[indexPath.row]).userInfo objectForKey:@"File" ] sing];
//        model.name = [(FileModel *)self.finshArr[indexPath.row] fileName];
        
        model = self.finshArr[indexPath.row];
        
        cell.textLabel.text = model.name;
        cell.detailTextLabel.text = model.singerName;
    }
    
    return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"正在下载";
    }else{
        return @"下载完成";
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1){
        if(self.finshArr.count == 0)return;

        ZCDetailListModel *model = [[ZCDetailListModel alloc] init];
     
//        model.name = [(FileModel *)[((ASIHTTPRequest *)[ZCDownLoadTool shareDownLoad].finishArr[indexPath.row - self.finshArr.count ]).userInfo objectForKey:@"File" ] fileName];
//        
//        model.singerName = [(FileModel *)[((ASIHTTPRequest *)[ZCDownLoadTool shareDownLoad].finishArr[indexPath.row - self.finshArr.count ]).userInfo objectForKey:@"File" ] sing];
        
//        model.name = [(FileModel *)self.finshArr[indexPath.row] fileName];
        model = self.finshArr[indexPath.row];
        
        NSString *str = [NSString stringWithFormat:@"%@/%@",SAVEDocument,model.name];
        [ZCPlayMusicTool getLocal:str];
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:model.name,@"name",model.singerName,@"nameSinge",model.auditionList[0][@"url"],@"url",nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:self userInfo:dic];
        [[NSUserDefaults standardUserDefaults] setObject:model.auditionList[0][@"url"] forKey:@"url"];
        
        [ZCPlayMusicTool sharePlay].pross = @"0";
//
        
    }

}



-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    if (editing) {
        [self.editButtonItem setTitle:@""];
        [self.editButtonItem setImage:[UIImage imageNamed:@"iconfont-xiugai"]];
        
    }else {
        [self.editButtonItem setTitle:@""];
        [self.editButtonItem setImage:[UIImage imageNamed:@"iconfont-shanchu"]];
    }
    [self.tableView setEditing:editing animated:YES];
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
-(UITableViewCellEditingStyle )tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(editingStyle == UITableViewCellEditingStyleDelete){
        if(indexPath.section == 1){
            [self.finshArr removeObjectAtIndex:indexPath.row];
            [NSKeyedArchiver archiveRootObject:self.finshArr toFile:LOCALDocument];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        }
    }
}




















- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
